package cn.mabach.member.service.impl;



import cn.mabach.member.dao.MemberDao;
import cn.mabach.member.entity.MemberEntity;
import cn.mabach.member.service.MemberService;
import cn.mabach.result.RS;
import cn.mabach.result.TableDataInfo;
import cn.mabach.utils.JwtDecode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    private static final String AUTHORIZE_TOKEN = "Authorization";

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private MemberDao memberDao;

    @Override
    public String getUser(HttpServletRequest request) {
        String token = request.getHeader(AUTHORIZE_TOKEN);
        if (StringUtils.isEmpty(token)){
            return null;
        }
        String user_name = null;
        try {
            String decode = JwtDecode.decode(token);
            user_name = JSONObject.parseObject(decode).getString("user_name");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return user_name;
    }

    /*
     *分页查询
     * */
    @Override
    public TableDataInfo queryPage(@RequestParam(value = "username", required = false) String username,
                                   @RequestParam(value = "phone", required = false) String phone,
                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {


        IPage<MemberEntity> page = this.page(
                new Page<MemberEntity>(pageNum,pageSize),
                new QueryWrapper<MemberEntity>().eq(!StringUtils.isEmpty(username),"username",username)
                .eq(!StringUtils.isEmpty(phone),"phone",phone)
        );

        return new TableDataInfo(page);
    }



    /*
     *根据id查询
     * */
    @Override
//    @PreAuthorize("hasAnyAuthority('read')")
    public RS<MemberEntity> getByIdE(@RequestParam("id") Long id) {
            MemberEntity res = this.getById(id);

        return RS.ok(res);
    }

    @Override
    public RS<MemberEntity> getByIByqqOpenId(@RequestParam("openId") String openId) {
        MemberEntity qq = this.getOne(new QueryWrapper<MemberEntity>().eq("qq_open_id", openId));
        return RS.ok(qq);
    }

    @Override
    public RS<MemberEntity> getMemberByUsername(@RequestParam("username") String  username) {
        MemberEntity member = this.getOne(new QueryWrapper<MemberEntity>().eq("username", username));

        return RS.ok(member);
    }

    @Override
    public RS<MemberEntity> getByMobile(@RequestParam("mobile") String mobile) {
        MemberEntity phone = this.getOne(new QueryWrapper<MemberEntity>().eq("phone", mobile));
        return RS.ok(phone);
    }

    /*
     *新增
     * */
    @Override
    public RS saveE(@RequestBody  MemberEntity entity) {
        boolean b = this.save(entity);
        if (!b){
            return RS.error();
        }
        return RS.ok();
    }

    /*
     *根据id更改
     * */
    @Override
    public RS updateByIdE(@RequestBody MemberEntity entity) {
        boolean b = this.updateById(entity);
        if (!b){
            return RS.error();
        }
        return RS.ok();
    }

    /*
     *根据id集合删除
     * */
    @Override
    @Transactional
    public RS removeByIdsE(@RequestParam("ids") List<Long> ids) {
        boolean b = this.removeByIds(ids);
        if (!b){
            return RS.error();
        }
        return RS.ok();
    }

    @Override
    public RS<List<String>> getPermsByUsername(@RequestParam("username") String username) {
        List<String> perms = memberDao.findPermsByUsername(username);
        return RS.ok(perms);
    }

    @Override
    public RS saveByOpenId(@RequestParam("username") String username,@RequestParam("password") String password,@RequestParam("openId") String openId) {
        MemberEntity entity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", username));
        if (entity==null){
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setUsername(username);
            memberEntity.setPassword(bCryptPasswordEncoder.encode(password));
            memberEntity.setQqOpenId(openId);
            boolean b = this.save(memberEntity);
            if (!b){
                return RS.error();
            }
            return RS.ok();
        }

        if (!bCryptPasswordEncoder.encode(password).equals(entity.getPassword())){
            return RS.error("密码错误");
        }

        entity.setQqOpenId(openId);
        boolean b = this.updateById(entity);
        if (!b){
            return RS.error();
        }

        return RS.ok();
    }


}